package ar.uba.fi.tonyvaliente.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ar.uba.fi.tonyvaliente.documents.Document;
import ar.uba.fi.tonyvaliente.web.manager.DocumentViewManager;

/**
 * Servlet implementation class for Servlet: DocumentView
 *
 */
 public class DocumentView extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private static Log log = LogFactory.getLog(DocumentView.class);
   
	public DocumentView() {
		super();
	}   	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		log.info("DocumentView IN");
		String documentID = request.getParameter("documentID");
		
		String message = null;
		
		try{
			log.debug("Buscando el documento: " + documentID);
			if(documentID != null){
				int docID;
				try{
					docID = Integer.parseInt(documentID);
				}catch(NumberFormatException nfe){
					message = "The document ID it's not valid";
					throw new Exception();
				}
				
				DocumentViewManager manager = new DocumentViewManager();
				
				Document document = manager.getDocument(docID);
				
				request.setAttribute("document", document);
			}else{
				message = "The Document ID is missing";
			}
		
		}catch(Exception e){
			if(message == null){
				message = e.getMessage();
			}
		}
		request.setAttribute("message", message);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("viewDocument.jsp");
		dispatcher.forward(request, response);
	
	}
}